package com.example.springbootmybatisdemo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description TODO
 * @Author: cdd
 * @Date: 2020/7/3 14:37
 * @Version: 1.0
 */
@Controller
@Slf4j
public class AccountController {

    // 登录页面
    @RequestMapping(value = "/toLogin")
    public String defaultLogin() {
        return "login";
    }

    // 登录处理
    @PostMapping(value = "/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) throws UnknownAccountException, IncorrectCredentialsException, LockedAccountException {
        // 从SecurityUtils里边templates创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:index";
        }

        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 执行认证登陆
        try {
            // 登录认证成功会自动重定向到"/index"
            subject.login(token);
            return "redirect:index";
        } catch (ExcessiveAttemptsException eae) {
            log.error("用户名或密码错误次数过多");

        } catch (AuthenticationException ae) {
            log.error("用户名或密码不正确");
        }
        return "login";
    }

    // 首页
    @GetMapping("/index")
    public String index(){
        return "index";
    }

    // 生成验证码，登录时用
    @GetMapping("/captcha_img")
    public void create(HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(116, 36, 4, 5);
        //得到code
        String code = captcha.getCode();
        System.out.println(code);
        //放到session
//        session.setAttribute("code", code);
        ServletOutputStream outputStream = response.getOutputStream();
        captcha.write(outputStream);
        outputStream.close();
    }
}
